package cn.wolfcode.luowowo.article.service.impl;

import cn.wolfcode.luowowo.article.domain.Travel;
import cn.wolfcode.luowowo.article.domain.TravelContent;
import cn.wolfcode.luowowo.article.mapper.TravelContentMapper;
import cn.wolfcode.luowowo.article.mapper.TravelMapper;
import cn.wolfcode.luowowo.article.query.TravelQuery;
import cn.wolfcode.luowowo.article.service.ITravelService;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;

@Service
public class TravelServiceImpl implements ITravelService {
    @Autowired
    private TravelMapper travelMapper;

    @Autowired
    private TravelContentMapper travelContentMapper;

    public PageInfo query(TravelQuery qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize(), qo.getOrderBy());

        return new PageInfo(travelMapper.selectForList(qo));
    }

    public Travel get(Long id) {
        Travel travel = travelMapper.selectByPrimaryKey(id);
        travel.setTravelContent(travelContentMapper.selectByPrimaryKey(id));
        return travel;

    }

    public List<Travel> queryViewNumTop3(Long destId) {
        return travelMapper.selectViewNumTop3(destId);
    }

    public Long saveOrUpdate(Travel travel) {
        //最后更新时间
        travel.setLastUpdateTime(new Date());

        // 摘要
        TravelContent travelContent = travel.getTravelContent();
        String contentStr = travelContent.getContent();
        if (contentStr.length() > 200){
            travel.setSummary(contentStr.substring(0,200));
        } else {
            travel.setSummary(contentStr);
        }

        if (travel.getId() == null) {
            // 创建时间
            travel.setCreateTime(new Date());
            travelMapper.insert(travel);
            // 内容
            travelContent.setId(travel.getId());
            travelContentMapper.insert(travelContent);
        } else {
            travelMapper.updateByPrimaryKey(travel);
            // 内容
            travelContent.setId(travel.getId());
            travelContentMapper.updateByPrimaryKey(travelContent);
        }
        return travel.getId();
    }

    public List<Travel> list() {
        return travelMapper.selectAll();
    }

    @Override
    public Travel getCoverUrlById(Long travelId) {
        return travelMapper.getcoverUrl(travelId);
    }
    public List<Travel> queryByDestId(Long destId) {
        return travelMapper.queryByDestId(destId);
    }

    public List<Travel> queryTravels(List<Long> tids) {
        if (tids == null || tids.size()<=0){
            return null;
        }
        return travelMapper.selectByIds(tids);
    }
}
